// 鉴权文件，负责显示满足特定条件的路由展示
import router from "@/routers/index.ts";
// 引入进度条
// @ts-ignore
import nprogress from "nprogress";
import "nprogress/nprogress.css";
nprogress.configure({ showSpinner: false });

import pinia from "@/store/index.ts";
import useUserStore from "@/store/modules/user";
import setting from "./setting";

const userStore = useUserStore(pinia);

router.beforeEach(async (to, from, next) => {
    document.title = `${setting.title} - ${to.meta.title}`;
    nprogress.start();
    const token = userStore.token;
    const username = userStore.username;
    // 判断已经登录
    if (token) {
        // 登录成功
        if (to.path === "/login") {
            // 不允许用户再次进入登录页，自动跳转到首页
            next({ path: "/" });
        } else {
            // 用户在登录成功后，必须确保用户信息以获取
            if (username) {
                next();
            } else {
                try {
                    await userStore.useInfo();
                    next();
                } catch {
                    // 获取用户信息失败，退出重新登录
                    userStore.userLogout();
                    next({ path: "/login", query: { redirect: to.path } });
                }
            }
        }
    } else {
        // 用户还未登录
        if (to.path === "/login") {
            next();
        } else {
            next({ path: "/login", query: { redirect: to.path } });
        }
    }
});

// 全局后置路由导航守卫
router.afterEach((to, from) => {
    nprogress.done();
});
